/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package vn.edu.iuh.dhth7dlt.emailclient.utils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 *
 * @author Friendless
 */
public class TCP {

    Socket socket;
    InputStream receive;
    OutputStream sendCommand;

    /**
     *
     * @param server
     * @param port
     * @throws IOException
     * @throws EmailExceptions
     */
    public TCP(String server, int port) throws IOException, EmailExceptions {
        try {
            socket = new Socket(server, port);
        } catch (UnknownHostException ex) {
            throw new EmailExceptions()
                    .set_error(String.format("Lỗi không kết nối được máy chủ email {0}-port:{1}", server, port));
        }
        receive = socket.getInputStream();
        sendCommand = socket.getOutputStream();
        //Kiểm tra server tình trạng server
        String response = this.getResponse();
        if (!response.startsWith("+OK")&&!response.startsWith("220")) {
            throw new EmailExceptions().set_error("Không thể kết nối tới máy chủ");

        }
    }

    String request(String request)  {
        sendRequest(request + "\r\n");
        System.out.print(request);
        return getResponse();
    }

    private String getResponse() {
        try {           
            int dataSize;
            while ((dataSize = receive.available()) <= 0);
            byte[] recvBuff = new byte[dataSize];
            receive.read(recvBuff, 0, dataSize);
            String response = new String(recvBuff, 0, dataSize);
            System.out.println(response);
            return response;
        } catch (IOException e) {
            System.err.println("IO exception in getResponse()");
            return "";

        }
    }

    public String getNextResponse() {
        return getResponse();
    }

    private void sendRequest(String request) {
      try{
       byte[] sendBuff = new byte[request.length()];
       sendBuff = request.getBytes();
       sendCommand.write(sendBuff, 0, sendBuff.length);
     } catch(IOException e){
      System.err.println("IO exception in sendRequest()");
     }
    }

    void close() throws IOException {
        sendCommand.close();
        receive.close();
        socket.close();
    }
}
